package monster.comm.key;


import monster.comm.log.ILog;
import monster.comm.log.LogService;
import monster.comm.util.SpringApplicationContextFactory;
import monster.flight.admin.manager.service.xtgl.KeyService;
import monster.flight.comm.entity.vo.Keytable;

import org.springframework.dao.InvalidDataAccessResourceUsageException;
/**
 * <p>Title: 系统框架设计</p>
 * <p>Description: </p>
 * <p>Copyright: Copyright (c) 2003</p>
 * <p>Company: </p>
 * @author 蒋增奎
 * @version 1.0
 */

public class KeyInfo {
 private static ILog log = LogService.getLog(KeyInfo.class);
  private int keyMin;
  private int keyMax;
  private int nextKey;
  private int poolSize;
  private String keyName;
  /**
   * 初始化
   * @param poolSize
   * @param keyName
   */
  public KeyInfo(int poolSize,String keyName)  {
    this.poolSize=poolSize;
    this.keyName=keyName;
    initFromDB();
  }

public int getNextKey() {
    if(nextKey>keyMax){
      initFromDB();
    }
    return nextKey++;
  }
  /**
   * 从数据库里提取数据
   * @param keyName
   */
	private void initFromDB() {
		try {
			KeyService keyService = (KeyService) SpringApplicationContextFactory
					.getService("keyService");
			Keytable keytable = new Keytable();
			keytable.setCur_val(String.valueOf(poolSize));
			keytable.setKeyname(keyName);
			keyService.update(keytable);
			keytable = keyService.getPoByID(keyName);
			if (keytable != null) {
				keyMax = Integer.parseInt(keytable.getCur_val());
				keyMin = keyMax - poolSize + 1;
				nextKey = keyMin;
			} else {
				log.error("没有这个序列号名");
				throw new InvalidDataAccessResourceUsageException("没有这个序列号名");

			}
		} catch (Exception e) {
			throw new InvalidDataAccessResourceUsageException(e.getMessage(),e);
		}

	}
 
 }
